<?php

/*
 * Table/AvenantTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Avenant;

class AvenantTable extends AbstractTableGateway {

    protected $table = 'rh_avenant';

    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Avenant($adapter));
	$this->initialize();
    }

    public function getAll() {
	return $this->select();
    }

    public function get($id) {
	$row = $this->select(array('id' => $id))
		->current();
	if (!$row)
	    throw new \Exception("Impossible de trouver #$id");

	return $row;
    }

    public function save(Avenant $avenant) {
	$data	 = array(
	    'hebdo'		 => $avenant->hebdo,
	    'taux'		 => $avenant->taux,
	    'debut'		 => $avenant->debut,
	    'fin'		 => $avenant->fin,
	    'poste_id'	 => $avenant->poste_id,
	    'site'	 => $avenant->site,
	    'niveau'	 => $avenant->niveau,
	    'college'	 => $avenant->college,
	    'echelon'	 => $avenant->echelon,
            'libelle'	 => $avenant->libelle,
            'avenant_file' => $avenant->avenant_file
	);
	$id	 = (int) $avenant->id;
	if ($id == 0){
	    $this->insert($data);
	    return $this->getLastInsertValue();
	}
	elseif ($this->get($id)){
	    $this->update($data, array('id' => $id));
	    return $id;
	}
	else{
	    throw new \Exception("Impossible de trouver #$id");
	}
    }

    public function erase($id) {
	$this->delete(array('id' => $id));
    }

    public function executeQuery($sql) {
	return $this->adapter
			->query($sql)
			->execute();
    }
    
    /**
     * Avenant
     * 
     * @param int $matricule
     * @param string $date
     * @return Avenant
     */
    public function getAvenantByDate($matricule, $date){
	$sql = "SELECT a.* FROM rh_avenant a, rh_employe e, rh_avenant_history h "
		. "WHERE h.avenant_id = a.id AND h.matricule = e.matricule "
		. "AND e.matricule = $matricule AND '$date' BETWEEN a.debut AND a.fin "
		. "ORDER BY a.id ASC" ;
	//var_dump($sql);
	$result = $this->getAdapter()
		->query($sql)
		->execute();
	$avenants = array();
	foreach($result as $row){
	    $avenants[] = new Avenant($this->getAdapter(), $row);
	}
	if(isset($avenants[0])){
	    return $avenants[0];
	}
	return NULL;
    }
}

?>
